<script lang="ts" setup>
import RecursiveMenuItem from './RecursiveMenuItem.vue';
import { ref, onMounted, Ref } from 'vue';
import { getLastPathSegment } from '../utils.ts'
import menuListStore from "../../stores/menuListStore.ts";
import { useRoute, useRouter } from 'vue-router';


interface MenuItem {
  path: string;
  name: string;
  icon: string;
  children?: MenuItem[];
}

const route = useRoute()
const router = useRouter()
const selectedKeys = ref<string[]>(['']);
const openKeys:Ref = ref<string[]>([]);

const menuStore = menuListStore()
const menuList:Ref = ref(menuStore.list)

function handleClickMenu({ item, keyPath }:{item:any,key:any,keyPath:any}){
  menuStore.setActiveMenuInfo(item)
  menuStore.updateKeyPath(keyPath)
  const path = keyPath.join('/').replace(/\/+/g, '/')
  router.push({path})

  // console.log('key', key)
  // console.log('keyPath', keyPath)
  // nextTick(()=>{
  console.log('selectedKeys', selectedKeys.value)
  // })
}

function findParentPath(menuList: MenuItem[], path: string): string | null {
  for (let i = 0; i < menuList.length; i++) {
    const menuItem = menuList[i];
    if (menuItem.path === path) {
      // 如果当前节点的路径与目标路径匹配，则返回最外层父节点的路径
      return menuItem.path;
    }
    if (menuItem.children && menuItem.children.length > 0) {
      // 递归查找子节点
      const parentPath = findParentPath(menuItem.children, path);
      if (parentPath !== null) {
        // 如果在子节点中找到了目标路径，则返回当前节点的路径
        return menuItem.path;
      }
    }
  }
  return null; // 没有找到匹配的父节点
}

onMounted(()=>{
  selectedKeys.value = [getLastPathSegment(route.path)]
  openKeys.value = [findParentPath(menuList.value, getLastPathSegment(route.path))]
})
</script>

<template>
  <div class="logo" >
    管理系统
  </div>
  <a-menu v-model:selectedKeys="selectedKeys"
          v-model:openKeys="openKeys"
          @click="handleClickMenu"
          class="menu"
          theme="dark"
          mode="inline">
    <recursive-menu-item v-for="item in menuList" :key="item.path" :item="item" />
  </a-menu>
</template>


<style scoped lang="scss">
.logo {
  width: 100%;
  height: 40px;
  color: #ffffff;
  font-size: 15px;
  display: flex;
  margin: 10px 0;
  justify-content: center;
  align-items: center;
}
</style>
